# -*- coding: utf-8 -*-
import wsgiref.handlers
import cgi
import re
import datetime
import base64
import urllib
import os

from datetime import *

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import memcache

from google.appengine.ext.webapp import template

from xml.etree.ElementTree import fromstring
guids = []
old_guid = ""

from database import *

class GetNicoLive(webapp.RequestHandler):
  def postTwitter(self,status,user,password):
    header_auth = { 'Authorization' : 'Basic ' + base64.b64encode('%s:%s' % (user, password)) }
    url    = 'http://twitter.com/statuses/update.json'
    data   = urllib.urlencode({ 'status' : status.encode('utf-8'), })
    result = urlfetch.fetch(url = url,method = urlfetch.POST,payload = data,headers = header_auth,)
    return result
  def recent(self,search,tab,page):
    url = 'http://live.nicovideo.jp/recent/rss?tab=%s&sort=start&p=%d' % (tab , page)
    
    xml = urlfetch.fetch(url).content
    elementtree = fromstring(xml)
    items = elementtree.findall(".//item")
    count = 0
    old_guid = memcache.get(key="guids")
    if isinstance(old_guid,basestring) == False:
      old_guid = ""
    
    for item in items:
      show = BroadcastShow()
      
      show.title = item.findtext("title")
      show.description = item.findtext("description")
      show.category = item.findtext("category")
      show.guid = item.findtext("guid")
      show.pubDate = datetime.strptime(item.findtext("pubDate"),"%a, %d %b %Y %H:%M:%S +0900")
      show.community_name = item.findtext("{http://live.nicovideo.jp/}community_name")
      show.community_id = item.findtext("{http://live.nicovideo.jp/}community_id")
      show.member_only = item.findtext("{http://live.nicovideo.jp/}member_only")
      show.owner_name = item.findtext("{http://live.nicovideo.jp/}owner_name")
      
      guids.append(show.guid)
      
      if (item.findtext("{http://live.nicovideo.jp/}type") == "community") & (old_guid.find(show.guid) == -1):
        for str in search:
          if (show.title+show.description+show.community_name+show.community_id).find(str) != -1:
            self.postTwitter(u"放送開始 : %s http://nico.ms/%s (%s) #%s" % (show.title, show.guid, show.community_name, show.guid), "lightnovel_live", "xxxxx")
            show.put()
      else:
        count += 1
    
    return count
  def get(self):
    tabs = ['common','try','live','req','r18']
    memcache.set(key="guids_", value= "", time=3600)
    old_guid = memcache.get(key="guids")
    for tab in tabs:
      page = 1
      count = 0
      
      while (count < 10)&(page < 5):
        count = self.recent([u"ライトノベル",u"ラノベ"],tab,page)
        self.response.out.write("%s-%d(%d)<br>" % (tab,page,count))
        page += 1
    memcache.set(key="guids", value= "|".join(guids), time=3600)


def main():
  application = webapp.WSGIApplication( [('/cron/nicolive', GetNicoLive)],
                                        debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
